<template>
	<view class="content">
		<view class="padding flex justify-between">
			<!-- <view class="color-green text-lg">
				一键填充历史订单信息
			</view>
			<view>
				<uv-button size="mini" color="#0BCA89" iconColor="#fff" icon="arrow-rightward"
					@click="openPop"></uv-button>
			</view> -->
			<view class="left-bgt padding-lr padding-tb-xs margin-right">
				如有疑惑，点击联系我们
			</view>
			<view class="right-bgt padding-lr padding-tb-xs" @click="openPop">
				查询之前订单
			</view>
		</view>
		<uv-form labelPosition="left" labelWidth="120" :model="formData"
			:labelStyle="{color: '#999999', 'font-weight': '600'}" :rules="rules" ref="form">
			<view class="bg-white padding-lr">
				<!-- <uv-form-item label="订单任务" borderBottom :required="true" :customStyle="customStyle">
					<uv-input v-model="formData.orderName" border="none">
					</uv-input>
				</uv-form-item> -->
				<uv-form-item label="姓名" prop="regionContact" borderBottom :required="true" :customStyle="customStyle">
					<uv-input v-model="formData.regionContact" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="手机号码" prop="regionPhone" borderBottom :required="true" :customStyle="customStyle">
					<uv-input v-model="formData.regionPhone" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="作业地址" prop="address" borderBottom :required="true" :customStyle="customStyle"
					@click="chooseLocation">
					<uv-input v-model="formData.address" disabled disabledColor="#ffffff" border="none">
					</uv-input>
					<template v-slot:right>
						<!-- <uv-icon name="cuIcon-locationfill"></uv-icon> -->
						<text class="cuIcon-locationfill"></text>
					</template>
				</uv-form-item>
				<uv-form-item label="详细地址" prop="detailAddress" borderBottom :customStyle="customStyle">
					<uv-textarea :maxlength="-1" autoHeight v-model="formData.detailAddress" border="none">
					</uv-textarea>
				</uv-form-item>
				<uv-form-item label="作业类型" prop="homeworkTypeName" borderBottom :required="true"
					:customStyle="customStyle" @click="showJobTypeSelect">
					<uv-input v-model="formData.homeworkTypeName" disabled disabledColor="#ffffff" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item :label="formData.homeworkType == 1?'作物种类':'货物类型'" prop="cropName" borderBottom
					:required="true" :customStyle="customStyle" @click="showTypeSelect">
					<uv-input v-model="formData.cropName" disabled disabledColor="#ffffff" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<template v-if="formData.homeworkType == 1">
					<uv-form-item label="作业面积" prop="area" borderBottom :required="true" :customStyle="customStyle">
						<uv-input type="digit" v-model="formData.area" border="none" @input="onInputChange">
						</uv-input>
						<template v-slot:right>
							<text>亩</text>
						</template>
					</uv-form-item>
					<uv-form-item label="推荐亩用量" prop="cropAcreUsage" borderBottom :required="true"
						:customStyle="customStyle">
						<uv-input type="digit" v-model="formData.cropAcreUsage" border="none" @input="onInputChange1">
						</uv-input>
						<template v-slot:right>
							<text>L</text>
						</template>
					</uv-form-item>
					<uv-form-item label="药物要求" prop="drugRequire" borderBottom :customStyle="customStyle">
						<uv-input type="digit" v-model="formData.drugRequire" border="none">
						</uv-input>
					</uv-form-item>
				</template>
				<template v-if="formData.homeworkType == 2">
					<!-- <uv-form-item label="货物类型" prop="cropName" borderBottom :required="true" :customStyle="customStyle">
						<uv-input v-model="formData.cropName" border="none" @input="onInputChange">
						</uv-input>
					</uv-form-item> -->
					<uv-form-item label="吊运重量" prop="area" borderBottom :required="true" :customStyle="customStyle">
						<uv-input type="digit" v-model="formData.area" border="none" @input="onInputChange">
						</uv-input>
						<template v-slot:right>
							<text>吨</text>
						</template>
					</uv-form-item>
				</template>
				<!-- <uv-form-item label="推荐作业时间" prop="homeworkStartTime" borderBottom :required="true"
					:customStyle="customStyle" @click="openTime('homeworkStartTime')">
					<uv-input v-model="formData.homeworkStartTime" disabled disabledColor="#ffffff" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item> -->
				<uv-form-item label="推荐作业时间" prop="dockingPeopleTime" borderBottom :required="true"
					:customStyle="customStyle" @click="openTime('dockingPeopleTime')">
					<uv-input v-model="formData.dockingPeopleTime" disabled disabledColor="#ffffff" border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="备注" prop="delayReason" borderBottom :customStyle="customStyle">
					<uv-textarea :maxlength="-1" autoHeight v-model="formData.delayReason" border="none">
					</uv-textarea>
				</uv-form-item>
			</view>

		</uv-form>
		<uv-action-sheet ref="typeSelect" :actions="actions" :title="actionsTitle" @select="typeConfirm">
		</uv-action-sheet>

		<uv-action-sheet ref="jobTypeSelect" :actions="actionsHw" title="请选择作业类型" @select="jobTypeConfirm">
		</uv-action-sheet>

		<uv-datetime-picker ref="datetimePicker" :minDate="minDate" :maxDate="1786778555000" v-model="dateValue"
			mode="datetime" @confirm="confirmTime">
		</uv-datetime-picker>

		<view class="foot-box">
			<view class="flex align-center justify-between solid-bottom padding-sm">
				<view class="">
					<text>单价</text>
					<text
						class="color-red text-lg text-bold">￥{{formData.price||'-'}}/{{formData.homeworkType==1?'亩':'吨'}}</text>
				</view>
				<view class="">
					<text>起步价</text>
					<text class="color-red text-lg text-bold">￥{{formData.startingPrice||'-'}}</text>
				</view>
				<view class="">
					<view class="flex align-center" @click="showModal">
						<uv-icon name="question-circle-fill" color="#0BCA89" size="20"></uv-icon>
						价格说明
					</view>
					<!-- <text class="color-red text-lg text-bold">￥{{formData.discountAmount|| '-'}}</text> -->
				</view>
			</view>
			<view class="flex align-center justify-between padding-sm">
				<view class="margin-left margin-right-lg">
					<view class="text-black text-sm text-center">
						预估总价
					</view>
					<view class="color-red text-center">
						<text class="text-lg text-bold">{{formData.money || '-'}}</text>
						<text class="text-sm">元</text>
						<text class="reduce-m text-gray"
							v-if="formData.totalAmount>formData.money">￥{{formData.totalAmount || '-'}}</text>
					</view>
				</view>
				<button class="cu-btn bg-green flex-sub" @click="submit">提交</button>
			</view>
		</view>

		<HistoryPopup ref="historyPopup" @selected="onSelected" />
		<MapPopup ref="mapPopup" @selectedAddr="addrBack" />
		<PriceDetailModal ref="priceDetailModal" />
	</view>
</template>
<script>
	import HistoryPopup from './HistoryPopup.vue'
	import PriceDetailModal from "@/components/priceDetailModal/index"
	import {
		selectDictLabel
	} from '@/utils/huida.js'
	import MapPopup from './MapPopup.vue'
	export default {
		// dicts: ["homework_type"],
		components: {
			HistoryPopup,
			MapPopup,
			PriceDetailModal
		},
		data() {
			return {
				actionsTitle: '请选择作物种类',
				customStyle: {
					padding: '15px 0'
				},
				minDate: Date.now(),
				addName: '',
				formData: {
					"orderName": "",
					"regionContact": "",
					"regionPhone": "",
					"cropType": "",
					"cropName": "",
					"homeworkType": "",
					"homeworkTypeName": "",
					"money": 0,
					"totalAmount": 0,
					"price": "",
					"startingPrice": "",
					"acreUsage": "",
					"discountAmount": "",
					"address": "",
					"detailAddress": "",
					"area": "",
					"cropAcreUsage": "",
					"drugRequire": "",
					"homeworkStartTime": "",
					"dockingPeopleTime": "",
					"lng": "",
					"lat": ""
				},
				dateValue: Number(new Date()),
				actionsHw: [],
				actions: [],
				cropTypeOpt: [],
				liftingTypeOpt: [],
				rules: {
					'orderName': {
						type: 'string',
						required: true,
						message: '请输入订单任务',
						trigger: ['blur', 'change']
					},
					'regionContact': {
						type: 'string',
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					'regionPhone': {
						type: 'string',
						required: true,
						message: '请输入手机号码',
						trigger: ['blur', 'change']
					},
					'area': {
						type: 'string',
						required: true,
						message: '请输入',
						trigger: ['blur', 'change']
					},
					'homeworkTypeName': {
						type: 'string',
						required: true,
						message: '请选择作业类型',
						trigger: ['blur', 'change']
					},
					'dockingPeopleTime': {
						type: 'string',
						required: true,
						message: '请选择推荐作业时间',
						trigger: ['blur', 'change']
					},
					'cropAcreUsage': {
						type: 'string',
						required: true,
						message: '请输入亩用量',
						trigger: ['blur', 'change']
					},
					'cropName': {
						type: 'string',
						required: true,
						message: '请选择',
						trigger: ['blur', 'change']
					},
					address: {
						type: 'string',
						required: true,
						message: '请上选择地址',
						trigger: ['blur', 'change']
					}
				},
				id: '',
				orderLogId: '',
				expId: '',
				isEdit: true,
				auditStatus: [],
				isTemporarily: '',
				timeName: ''
			}
		},
		// computed: {
		// 	actionsHw() {
		// 		return this.dict.type.homework_type?.map(item => ({
		// 			name: item.dictLabel,
		// 			value: item.dictValue 
		// 		}))
		// 	}
		// },
		onLoad(data) {
			console.log(data, 123)
			const user = uni.getStorageSync('userInfo')
			this.formData.regionContact = user.name
			this.formData.regionPhone = user.contact
			this.id = data.id
			this.orderLogId = data.orderLogId
			this.formData.startTime = data.homeworkStartTime
			this.formData.endTime = data.dockingPeopleTime
			this.isEdit = data.isEdit == "true" ? true : false
			uni.$uv.http.get('/cadre/highSeasOrder/cropType').then(res => {
				this.cropTypeOpt = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
			})
			uni.$uv.http.get('/system/dict/data/type/lifting_type').then(res => {
				this.liftingTypeOpt = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
			})
			uni.$uv.http.get('/system/dict/data/type/homework_type').then(res => {
				this.actionsHw = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
			})
			if (data.id) {
				this.fetchDetail()
			}
		},
		methods: {
			showModal() {
				if (!this.formData.cropType) return uni.showToast({
					title: this.formData.homeworkType == 1 ? '请选择作物种类' : '请选择货物类型',
					icon: 'none'
				})
				if (!this.formData.area) return uni.showToast({
					title: this.formData.homeworkType == 1 ? '请输入作业面积' : '请输入吊运重量',
					icon: 'none'
				})
				if (this.formData.homeworkType == 1 && !this.formData.cropAcreUsage) return uni.showToast({
					title: '请输入亩用量',
					icon: 'none'
				})
				this.$refs.priceDetailModal.show({
					cropType: this.formData.cropType,
					area: this.formData.area,
					cropAcreUsage: this.formData.cropAcreUsage,
					homeworkType: this.formData.homeworkType,
					homeworkTypeName: this.formData.homeworkTypeName
				})
			},
			selectDictLabel,
			openPop() {
				this.$refs.historyPopup.open()
			},
			goBack() {
				uni.navigateBack()
			},
			// 详情
			fetchDetail() {
				this.$http.get(`/cadre/assignOrder/getDatail`, {
					params: {
						id: this.id,
						...(this.$hd.position || {}),
					}
				}).then(res => {
					// res.data.cropName = selectDictLabel(this.actions, res.data.cropType)
					res.data.homeworkTypeName = selectDictLabel(this.actionsHw, res.data.homeworkType)
					if (res.data.orderName.indexOf(res.data.cropName) != -1) {
						const arr = res.data.orderName.split(res.data.cropName)
						this.addName = arr[0]
					} else {
						this.addName = ''
					}
					this.formData = res.data
				})
			},
			// 取消
			onCancel() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定取消该记录？',
					success: function(res) {
						if (res.confirm) {
							that.$http.get(`/cadre/orderException/cancel/${that.expId}`).then(res => {
								uni.showToast({
									title: '取消成功'
								})
								that.goBack()
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},
			// 暂存
			submitPre() {
				// const delayTs = new Date(this.formData.delayTime).getTime();
				// const endTs = new Date(this.formData.endTime).getTime();
				// if (delayTs < endTs) {
				// 	uni.showToast({
				// 		icon: 'error',
				// 		title: '延长结束时间不能早于原结束时间'
				// 	});
				// 	return;
				// }
				this.formData.isTemporarily = 1;
				const payload = {
					orderId: this.id,
					orderLogId: this.orderLogId,
					...this.formData,
					status: 4
				}
				this.$http.post('/cadre/orderException/add', payload)
					.then(res => {
						uni.showToast({
							icon: 'success',
							title: '暂存成功',
							duration: 1500,
							complete: () => {
								const pages = getCurrentPages();
								if (pages.length > 1) {
									uni.navigateBack();
								} else {
									uni.reLaunch({
										url: '/subPages\pages\exceptionList\index'
									});
									uni.navigateBack();
								}
							}
						})
					})
			},
			// 提交
			submit() {
				const user = uni.getStorageSync('userInfo')
				if (!user) {
					uni.$uv.route("/pages/public/login")
					return
				}
				// const delayTs = new Date(this.formData.homeworkStartTime).getTime();
				// const endTs = new Date(this.formData.dockingPeopleTime).getTime();
				// if (delayTs > endTs) {
				// 	uni.showToast({
				// 		icon: 'error',
				// 		title: '请检查作业时间！'
				// 	});
				// 	return;
				// }
				// 编辑
				// let url = 'cadre/highSeasOrder/edit'
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {
					this.formData.orderName = this.addName + this.formData.cropName + this.formData
						.homeworkTypeName + this.formData.area
					if (this.formData.homeworkType == 1) {
						this.formData.orderName += '亩'
					} else {
						this.formData.orderName += '吨'
					}
					let url = '/cadre/highSeasOrder/add'
					if (this.id) {
						url = '/cadre/highSeasOrder/edit'
					}
					this.$http.post(url, this.formData).then(res => {
						uni.showToast({
							icon: res.code === 200 ? 'success' : 'error',
							title: res.msg || '未知返回'
						})
						if (res.code === 200) {
							// 成功才返回上一级
							uni.navigateBack()
						}
					}).catch(err => {
						const msg =
							(err.response && err.response.data && err.response.data.msg) ||
							(err.data && err.data.msg) ||
							err.message ||
							'网络错误'
						uni.showToast({
							icon: 'error',
							title: msg
						})
					})
				}).catch(errors => {
					uni.showToast({
						icon: 'none',
						title: '请检查输入项是否完整'
					})
				})
			},
			// 重置
			reset() {
				this.$refs.form.resetFields();
				this.$refs.form.clearValidate();
			},
			openTime(n) {
				// if (!this.isEdit) return
				this.timeName = n
				this.$refs.datetimePicker.open();
			},
			confirmTime(e) {
				this.formData[this.timeName] = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
			},
			// 类型选择
			showTypeSelect() {
				// if (!this.isEdit) return
				this.$refs.typeSelect.open();
				this.hideKeyboard();
			},
			// 类型选择返回结果
			typeConfirm(e) {
				this.formData.cropType = e.value
				this.formData.cropName = e.name
				this.fetchMoney()
			},
			// 作业类型选择
			showJobTypeSelect() {
				// if (!this.isEdit) return
				this.$refs.jobTypeSelect.open();
				this.hideKeyboard();
			},
			// 作业类型选择返回结果
			jobTypeConfirm(e) {
				if (e.value == 1) {
					this.actions = this.cropTypeOpt
					this.actionsTitle = '请选择作物种类'
				} else {
					this.actions = this.liftingTypeOpt
					this.actionsTitle = '请选择货物物类型'
				}
				this.formData.homeworkType = e.value
				this.formData.homeworkTypeName = e.name
				// 重置金额和类型
				this.reloadData()
			},
			reloadData() {
				this.formData.money = 0
				this.formData.area = ''
				this.formData.cropName = ''
				this.formData.cropType = ''
				this.formData.totalAmount = 0
				this.formData.price = ''
				this.formData.startingPrice = ''
				this.formData.acreUsage = ''
				this.formData.cropAcreUsage = ''
				this.formData.discountAmount = ''
				this.formData.drugRequire = ''
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			chooseLocation() {
				this.$refs.mapPopup.open({
					lat: this.formData.lat || this.$hd.position?.lat || 22.83393,
					lng: this.formData.lng || this.$hd.position?.lng || 108.31343 //,
				})
			},
			onInputChange() {
				this.fetchMoney()
			},
			onInputChange1(e) {
				if (!this.formData.area || !e) return
				this.fetchMoney(e)
			},
			// 获取金额
			fetchMoney(v) {
				if (this.formData.homeworkType == 1 && (!this.formData.cropType || !this.formData.area)) return
				if (this.formData.homeworkType == 2 && !this.formData.area) return
				const fn = () => {
					this.$http.get('/cadre/highSeasOrder/sumAmount', {
						params: {
							orderType: 1,
							homeworkType: this.formData.homeworkType,
							cropType: this.formData.cropType,
							cropName: this.formData.cropName,
							area: this.formData.area,
							cropAcreUsage: v
						}
					}).then(res => {
						// console.log('获取金额', res)
						if (res.code != 200) return
						if (this.formData.homeworkType == 2) {
							this.formData.money = res.data.estimatedAmount
							this.formData.startingPrice = res.data.startingPrice || 0
							this.formData.price = res.data.price || 0
						} else {
							this.formData.totalAmount = res.data.totalAmount || 0
							this.formData.price = res.data.price || 0
							this.formData.startingPrice = res.data.startingPrice || 0
							this.formData.acreUsage = res.data.acreUsage || 0
							this.formData.cropAcreUsage = res.data.acreUsage || 0
							this.formData.discountAmount = res.data.discountAmount || 0
							if (res.data.estimatedAmount * 1 < res.data.startingPrice * 1) {
								this.formData.money = res.data.startingPrice
							} else {
								this.formData.money = res.data.estimatedAmount
							}
							// this.formData.money = res.data.estimatedAmount - this.formData.discountAmount
						}
					})
				}
				uni.$uv.debounce(fn, 500)
			},
			// 取消订单
			cancelOrder() {
				this.$http.get('cadre/highSeasOrder/cancel', {
					params: {
						id: this.orderId
					}
				}).then(res => {
					console.log('// 取消订单', res)
					uni.showToast({
						title: '订单取消成功！'
					})
				})
			},
			// 选择了订单
			onSelected(item) {
				console.log(item)
				// this.formData.orderName = item.orderName
				this.formData.regionContact = item.regionContact
				this.formData.regionPhone = item.regionPhone
				this.formData.cropType = item.cropType
				this.formData.money = item.money
				this.formData.address = item.address
				this.formData.detailAddress = item.detailAddress
				this.formData.area = item.area
				this.formData.cropAcreUsage = item.cropAcreUsage
				this.formData.drugRequire = item.drugRequire
				// "homeworkStartTime": item.homeworkStartTime
				this.formData.dockingPeopleTime = ''
				this.formData.lng = item.lng
				this.formData.lat = item.lat
				this.formData.homeworkType = item.homeworkType
				this.formData.homeworkTypeName = selectDictLabel(this.actionsHw, item.homeworkType)
				if (item.homeworkType == 1) {
					this.actions = this.cropTypeOpt
					this.actionsTitle = '请选择作物种类'
				} else {
					this.actions = this.liftingTypeOpt
					this.actionsTitle = '请选择货物物类型'
				}
				this.formData.cropName = item.cropName || selectDictLabel(this.actions, item.cropType)

				if (item.orderName.indexOf(this.formData.cropName) != -1) {
					const arr = item.orderName.split(this.formData.cropName)
					this.addName = arr[0]
				} else {
					this.addName = ''
				}
				console.log('this.addName', this.addName)
				this.fetchMoney()
			},
			addrBack(item) {
				this.formData.address = item.address
				this.formData.lng = item.location.lng
				this.formData.lat = item.location.lat
				this.addName = item.city + item.district
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding-bottom: 120px;
	}

	.left-bgt {
		font-weight: 500;
		font-size: 28rpx;
		color: #FEFEFE;
		background-image: url($imagesBasUrl+'/bg-xdleft.png');
		background-size: 100% 100%;
		animation-iteration-count: infinite; 
		animation-name: ctanm;
		animation-duration: 2s;
		animation-delay: 5s;
	}

	.right-bgt {
		font-weight: 500;
		font-size: 28rpx;
		color: #FEFEFE;
		background-image: url($imagesBasUrl+'/bg-xdright.png');
		background-size: 100% 100%;
	}

	.foot-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		// display: flex;
		// align-items: center;
		// justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
	}

	.color-red {
		color: #FE3A6A;
	}

	.reduce-m {
		text-decoration-line: line-through;
	}

	@keyframes ctanm {
		0% {
			transform: scale3d(1, 1, 1);
		}

		50% {
			transform: scale3d(1.05, 1.05, 1.05);
		}

		100% {
			transform: scale3d(1, 1, 1);
		}
	}
</style>